import React from 'react'
import { createHashHistory } from 'history'
import type { BrowserHistory } from 'history'

import { Router } from 'react-router'

export interface BrowserRouterProps {
	basename?: string
	children?: React.ReactNode
	window?: Window
}

const browserHistory = createHashHistory({ window })

const BrowserRouter: React.FC = ({ basename, children, window }: BrowserRouterProps) => {
	let historyRef = React.useRef<BrowserHistory>()
	if (historyRef.current == null) {
		historyRef.current = browserHistory
	}

	let history = historyRef.current
	let [state, setState] = React.useState({
		action: history.action,
		location: history.location,
	})

	React.useLayoutEffect(() => history.listen(setState), [history])

	return (
		<Router
			basename={basename}
			children={children}
			location={state.location}
			navigationType={state.action}
			navigator={history}
		/>
	)
}

export { browserHistory as history, BrowserRouter }
